﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using System.Runtime.InteropServices;

namespace BitwiseOre.SharedMemory.Core.Primatives
{
    internal sealed class SharedAllocator : IAllocator  
    {
        private readonly IntArrayCreator _intArrayCreator;
        private readonly AccessorCreator _accessorCreator;

        private int _currentOffset;

        public SharedAllocator(IntArrayCreator intArrayCreator,
                               AccessorCreator accessorCreator)
        {
            _intArrayCreator = intArrayCreator;
            _accessorCreator = accessorCreator;
        }

        public IIntArray AllocateIntArray(int count)
        {
            if (count <= 0) throw new ArgumentOutOfRangeException("count");

            var array = _intArrayCreator(_currentOffset, count);
            _currentOffset += array.Capacity;
            return array;
        }

        public IArray<T> AllocateArray<T>(int count)
            where T : struct 
        {
            if (count <= 0) throw new ArgumentOutOfRangeException("count");
            
            var sizeoft = Marshal.SizeOf(typeof (T));
            
            var array = new SharedArray<T>(_accessorCreator(_currentOffset, checked (count*sizeoft)));
            _currentOffset += array.Capacity;
            return array;
        }

        public IByteArray AllocateByteArray(int count)
        {
            if (count <= 0) throw new ArgumentOutOfRangeException("count");

            var array = new SharedByteArray(_accessorCreator(_currentOffset, count));
            _currentOffset += array.Capacity;
            return array;
        }
    }
}